package com.movie.service.impl;

import com.movie.entity.Movie;
import com.movie.entity.Review;
import com.movie.entity.User;
import com.movie.exception.ResourceNotFoundException;
import com.movie.exception.DuplicateReviewException;
import com.movie.mapper.MovieMapper;
import com.movie.mapper.ReviewMapper;
import com.movie.mapper.UserMapper;
import com.movie.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class ReviewServiceImpl implements ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Override
    public List<Review> getReviewsByMovieId(Long movieId) {
        return reviewMapper.findByMovieId(movieId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteReview(Long id, Long currentUserId) {
        Review review = reviewMapper.findById(id);
        if (review == null) {
            return false;
        }
        System.out.println("WARN: Delete review permission check not fully implemented.");
        return reviewMapper.deleteById(id) > 0;
    }

    @Override
    public List<Review> getReviewsByUserId(Long userId) {
        return reviewMapper.findByUserId(userId);
    }

    @Override
    public Map<String, Object> getAllReviewsPaged(int page, int size, String movieTitle, String username, Integer rating) {
        int offset = page * size;
        List<Review> reviews = reviewMapper.findAllPaged(size, offset, movieTitle, username, rating);
        int total = reviewMapper.countAllFiltered(movieTitle, username, rating);

        Map<String, Object> result = new HashMap<>();
        result.put("content", reviews);
        result.put("totalElements", total);
        return result;
    }

    @Override
    public Review createReview(Review review) {
        Review existingReview = reviewMapper.findByUserIdAndMovieId(review.getUserId(), review.getMovieId());
        if (existingReview != null) {
            throw new DuplicateReviewException("User has already reviewed this movie.");
        }
        review.setReviewTime(LocalDateTime.now());
        reviewMapper.insert(review);
        return review;
    }

    @Override
    @Transactional
    public Review updateReview(Long reviewId, Review reviewDetails, Long currentUserId) {
        Review existingReview = reviewMapper.findById(reviewId);
        if (existingReview == null) {
            throw new ResourceNotFoundException("Review not found with id: " + reviewId);
        }
        if (!existingReview.getUserId().equals(currentUserId)) {
            throw new RuntimeException("User is not authorized to update this review.");
        }
        existingReview.setRating(reviewDetails.getRating());
        existingReview.setComment(reviewDetails.getComment());
        int updatedRows = reviewMapper.update(existingReview);
        if (updatedRows == 0) {
            throw new RuntimeException("Failed to update review, possibly due to concurrent modification.");
        }
        return existingReview;
    }

    // 新增：管理员删除评论的实现
    @Override
    @Transactional
    public boolean deleteReviewAsAdmin(Long id) {
        Review review = reviewMapper.findById(id);
        if (review == null) {
            // 可以选择抛出 NotFoundException 或返回 false
            // throw new ResourceNotFoundException("Review not found with id: " + id);
             return false; 
        }
        return reviewMapper.deleteById(id) > 0;
    }
} 